package cn.amossun.starter.event.handler;

import cn.amossun.starter.event.annoation.EventListener;
import cn.amossun.starter.event.exception.EventConfigException;
import cn.amossun.starter.event.property.EventContext;
import cn.amossun.starter.event.property.ListenerContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;

/**
 * @description:
 * @author: Amos.Sun
 * @DateTime: 2020-02-10 17:39
 **/
@Data
@Slf4j
public class ListenerContextProcessor implements ListenerInvokeHolder<ListenerContext> {

    private final EventContext eventContext;

    private final RabbitAdmin rabbitAdmin;

    public ListenerContextProcessor(EventContext eventContext, RabbitAdmin rabbitAdmin) {
        this.eventContext = eventContext;
        this.rabbitAdmin = rabbitAdmin;
    }

    @Override
    public ListenerContext processListenerInvoke(Object bean, String beanName, Method method) {
        EventListener eventListener = AnnotationUtils.findAnnotation(method, EventListener.class);
        if (eventListener != null) {
            ListenerContext listenerContext = new ListenerContext(
                    eventListener.exclusive(),
                    eventListener.priority(),
                    eventListener.concurrency(),
                    eventListener.group(),
                    eventListener.autoStartup(),
                    eventListener.ackMode(),
                    eventListener.getClass(),
                    eventListener.reTry(),
                    eventListener.prefetchCount(),
                    getArguments(eventListener.arguments()),
                    rabbitAdmin);
            listenerContext.getQueueNames().addAll(getQueueNames(bean, beanName, method, eventListener));
            eventContext.getListenerContexts().add(listenerContext);

            return listenerContext;
        }
        throw new EventConfigException("not find @EventListener");
    }

    @Override
    public void processListener(Object bean, String beanName, Method method) {

    }
}
